import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import { Notify, Dialog } from "vant";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = encodeURIComponent(getToken())
    }
    config.headers['platform'] = 2
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // console.log('response', response);
    const res = response.data
    console.log(res.code);

    // if (res.code === 10003) {
    //   let token = getToken()
    //   console.log('token10003', token);
    //   if (token) {
    //     window.location.reload();
    //   } else {
    //     Dialog
    //       .alert({
    //         message: "登录已失效，请重新登录"
    //       })
    //       .then(() => {
    //         router.push({
    //           name: "login"
    //         });
    //       });
    //     return Promise.reject(res || 'Error')
    //   }
    // } else if (res.code == 90000) {
    //   console.log(111);
    //   Notify({
    //     type: "warning",
    //     message: res.msg
    //   });
    // } else if (response.config.url == '/ajax/agent/viewSign') {
    //   return res
    // } else {
    //   return res
    // }

    if ((res.code != 10003 || response.config.url == '/ajax/agent/viewSign') && res.code != 90000) {
      console.log(22222);
      return res
    } else if (res.code === 10003) {
      let token = getToken()
      console.log('token10003', token);
      if (token) {
        window.location.reload();
      } else {
        Dialog
          .alert({
            message: "登录已失效，请重新登录"
          })
          .then(() => {
            router.push({
              name: "login"
            });
          });
        return Promise.reject(res || 'Error')
      }
    } else if (res.code == 90000) {
      Notify({
        type: "warning",
        message: res.msg
      });
    } else {
      console.log('调用接口失败了', res.msg)
      Notify({
        type: "warning",
        message: res.msg
      });
    }
  },
  error => {
    console.log('err' + error) // for debug
    Notify({
      type: "warning",
      message: '网络太慢了，请重试'
    });
    return Promise.reject(error)
  }
)

export default service
